const express = require("express");
const router = express.Router();
const replyModel = require("../model/reply.js");
const diaryItemModel = require("../model/diaryItems.js");
const {send , sendErr} = require('./send');

router.get("/" , async function(req , res){ // 得到回复
    try {
        let { replyId, diaryItemId } = req.query;
        if (replyId) {
            let reply = await replyModel.findById(replyId);
            if (reply) {
                let data = { ...reply._doc };
                delete data.__v;
                send(res, { data });
            } else {
                sendErr(res, { msg: "该回复不存在" });
            }
        } else {
            let data = await replyModel.find({ diaryItemId }, { __v: 0 });
            send(res, { data });
        }
    } catch (error) {
        console.log(error);
        sendErr(res, { msg: "传入的数据可能有问题" });
    }
})

router.post("/create" , async function(req , res){ // 创建回复
    try {
        let { diaryItemId, content, createAt, authorId } = req.body;
        let diaryItem = await diaryItemModel.findById(diaryItemId);
        if (diaryItem) {
            let reply = await replyModel.create({
                authorId,
                diaryItemId,
                createAt,
                content
            })
            if (reply) {
                await diaryItemModel.findByIdAndUpdate(diaryItemId, { $push: { replyId: reply._id } });
                send(res, {
                    data: {
                        replyId: reply._id
                    }
                })
            } else {
                sendErr(res, { msg: "创建失败" });
            }
        } else {
            sendErr(res, { msg: "日记不存在" });
        }
    } catch (error) {
        console.log(error);
        sendErr(res, { msg: "传入的数据可能有问题" });
    }
})

module.exports = router;
